<template>
  <el-form
    ref="companyForm"
    :model="companyForm"
    :rules="rules"
    label-width="150px"
    class="demo-companyForm"
  >
    <el-form-item label="公司名称：" prop="companyName">
      <el-input
        v-model="companyForm.companyName"
        maxlength="30"
        @focus="hideErrMsg('companyName')"
      />
    </el-form-item>
    <el-form-item label="公司信用代码：" prop="creditCode">
      <el-input
        v-model="companyForm.creditCode"
        maxlength="18"
        @focus="hideErrMsg('creditCode')"
      />
    </el-form-item>
    <el-form-item label="法人代表：" prop="corporateName">
      <el-input
        v-model="companyForm.corporateName"
        maxlength="30"
        @focus="hideErrMsg('corporateName')"
      />
    </el-form-item>
    <el-form-item label="公司注册地址" prop="sellerAddrDetail">
      <el-input
        v-model="companyForm.sellerAddrDetail"
        maxlength="50"
        show-word-limit
        type="textarea"
        :rows="2"
        @focus="hideErrMsg('sellerAddrDetail')"
      />
      <!-- <el-input type="textarea" v-model="companyForm.desc"></el-input> -->
    </el-form-item>
    <!-- action	必选参数，上传的地址 要用：那是因为我们写的是基准地址，如果我们直接写127.0.0.1:3000/upload就不需要-->
    <!-- headers	设置上传的请求头部 -->
    <!-- file-list	上传的文件列表, 例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}] -->
    <el-form-item label="营业执照扫描件：" prop="licence" ref="licenceImage">
      <el-upload
        class="avatar-uploader"
        :action="options.action"
        :show-file-list="options.showFileList"
        :auto-upload="options.autoUpload"
        :accept="options.accept"
        :on-change="handleLicenceChange"
      >
        <img v-if="companyForm.licence" id="licence" :src="companyForm.licence" class="avatar" alt="">
        <img v-else src="../../../assets/images/license.png" alt class="avatar">
      </el-upload>
    </el-form-item>

    <el-form-item class="step">
      <div class="common last" @click="last">返回上一步</div>
      <div class="common next" v-if="!submit" @click="next">下一步</div>
      <div class="common next" v-else :loading="submit">保存中...</div>
    </el-form-item>
  </el-form>
</template>

<script>
import { stepOne } from '@/api/join'
import { creditCodeReg } from '@/js/regex'
import { checkCompanyName, checkCompanyCode } from '@/api/company'
export default {
  props: {
    companyForm: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      rules: {
        companyName: [
          {
            required: true, validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error(`公司名称不能为空`))
                return
              }
              if (value.length > 50) {
                callback(new Error(`公司名称不能超过30位`))
                return
              }
              checkCompanyName(value).then(response => {
                if (!response.data) {
                  callback(new Error(`"${value}" 已被占用`))
                } else {
                  callback()
                }
              })
            }, trigger: 'blur'
          }
        ],
        creditCode: [
          {
            required: true, validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error(`公司信用代码不能为空`))
                return
              }
              if (value.length > 18) {
                callback(new Error(`公司信用代码不能超过18位`))
                return
              }
              if (!creditCodeReg.test(value)) {
                callback(new Error(`公司信用代码格式不正确`))
                return
              }
              checkCompanyCode(value).then(response => {
                if (!response.data) {
                  callback(new Error(`"${value}" 已被占用`))
                } else {
                  callback()
                }
              })
            }, trigger: 'blur'
          }
        ],
        corporateName: [
          { required: true, message: '请输入公司法人代表', trigger: 'blur' },
          { max: 20, message: '公司法人代表不能超过20位', trigger: 'blur' }
        ],
        sellerAddrDetail: [
          { required: true, message: '请输入公司注册地址', trigger: 'blur' },
          { max: 50, message: '公司注册地址不能超过50位', trigger: 'blur' }
        ],
        licence: [
          {
            required: true, validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('请选择营业执照扫描件'))
                return
              }
              callback()
            }, trigger: 'change'
          }
        ]
      },
      options: {
        showFileList: false,
        autoUpload: false,
        accept: 'image/*',
        action: '#'
      },
      submit: false
    }
  },
  methods: {
    // 移除错误提示
    hideErrMsg(progName) {
      this.$refs['companyForm'].clearValidate(progName)
    },
    last() {
      this.$emit('lastFirst', 1)
    },
    next() {
      // 点击下一步
      this.$refs.companyForm.validate(valid => {
        if (valid) {
          this.submit = true
          const formData = new FormData()
          formData.append('companyName', this.companyForm.companyName)
          formData.append('creditCode', this.companyForm.creditCode)
          formData.append('sellerAddrDetail', this.companyForm.sellerAddrDetail)
          formData.append('corporateName', this.companyForm.corporateName)
          if (this.companyForm.businessImage) {
            formData.append('businessImage', this.companyForm.businessImage)
            formData.append('licence', new Blob([], { type: 'image/gif' }), this.companyForm.licenceName)
          } else {
            formData.append('licence', this.toBlob(this.companyForm.licence), this.companyForm.licenceName)
          }
          /* if (this.form.legalRepresent) {
              formData.append('legalRepresent', this.form.legalRepresent)
              formData.append('identity', new Blob([], { type: 'image/gif' }), this.fileName.identity)
            } else {
              formData.append('identity', this.toBlob(this.form.identity), this.fileName.identity)
            }*/
          stepOne(formData).then(res => {
            if (res.data) {
              sessionStorage.setItem('uuid', res.message)
              this.$emit('nextThird', 3)
            } else {
              this.submit = false
              this.$message.error('提交失败,请稍后重试')
            }
          }).catch(() => {
            this.submit = false
            this.$message.error('提交失败,请稍后重试')
          })
        }
      })
    },
    // 处理执照
    handleLicenceChange(file) {
      if (this.checkFile(file)) {
        this.companyForm.licenceName = file.raw.name
        const reader = new FileReader()
        reader.readAsDataURL(file.raw)
        reader.onload = () => {
          this.companyForm.licence = reader.result
          this.$refs.licenceImage.clearValidate()
          delete this.companyForm.businessImage
        }
      }
    },
    // 校验文件
    checkFile(file) {
      const type = file.raw.type
      const isPicture = type === 'image/jpeg' || type === 'image/png' || type === 'image/gif'
      const isLt3M = file.size / 1024 / 1024 < 3
      if (!isPicture) {
        this.$message.error('上传图片只能是 JPG/GIF/PNG 格式!')
      }
      if (!isLt3M) {
        this.$message.error('上传图片大小不能超过 3MB!')
      }
      return isPicture && isLt3M
    },
    // 构造文件流
    toBlob(dataURL) {
      const arr = dataURL.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const bStr = atob(arr[1])
      let n = bStr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bStr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    }
  }
}
</script>

<style scoped lang="scss">
  .avatar {
    width: 85px !important;
    height: 51px !important;
    // display: block;
  }

  ::v-deep .el-form-item__content {
    width: 400px;
  }

  .step {
    margin-top: 38px;
    ::v-deep .el-form-item__content {
      width: 400px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
    .common {
      width: 80px;
      height: 30px;
      border-radius: 4px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .common:hover {
      cursor: pointer;
    }
    .next {
      width: 100%;
      color: #ffffff;
      background-color: #ff3b30;
      height: 42px;
    }
    .last {
      width: 100%;
      color: #6b6b6b;
      height: 42px;
      background-color: #e5e5e5;
      margin-bottom: 15px;
    }
  }

  //  ::v-deep .el-upload--picture-card{
  // border: none;
  //   }
</style>
